#include "../Server.hpp"
#include <iostream>
#include <string.h>
#include <string>

std::unordered_map<uint64_t,ConnectionPtr> hash;
static uint64_t connid = 0;
EventLoop *pl = new EventLoop();// Poller对象:负责监听

void connection_cancel(const ConnectionPtr &cp)
{
    hash.erase(cp->GetConnid());// 这里有一个BUG
}

void connected_handle(const ConnectionPtr &cp)
{
    std::cout << cp->GetSockfd() << "号连接已连接!" << std::endl;
}

void message_handle(const ConnectionPtr &cp,Buffer *buf)
{
    std::string str;
    buf->Read(str);
    DEBUG_LOG("接收到新消息: %s",str.c_str());

    cp->Send((void *)str.c_str(),str.size());
}

void any_handle(const ConnectionPtr &cp)
{
    DEBUG_LOG("没啥事...");
}

void hendle_accept(int fd)
{
    std::cout << "获取到新连接: " << fd << std::endl;
    ++connid;
    ConnectionPtr conn(new Connection(pl,connid,fd));
    //conn->StartInactivBroken(3);

    conn->SetConnectedCallBack(std::bind(connected_handle,std::placeholders::_1));
    conn->SetServerClosedCallback(std::bind(connection_cancel,std::placeholders::_1));
    conn->SetAnyCallBack(std::bind(any_handle,std::placeholders::_1));
    conn->SetMessageCallBack(std::bind(message_handle,std::placeholders::_1,std::placeholders::_2));
    conn->Established();
    hash.insert(std::make_pair(connid,conn));
}

int main()
{
    Acceptor act(pl,9090);
    act.SetAcceptorCallBack(std::bind(hendle_accept,std::placeholders::_1));
    //act.Listen();
    pl->Start();// 该函数会将触发的Channel对象放入vector中

    return 0;
}